﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TTS工具
{
    public partial class FrmPlayTts : Form
    {
        Thread playTtsThread = null;
        bool isRun = false;
        public FrmPlayTts()
        {
            InitializeComponent();
        }

        private void FrmPlayTts_Load(object sender, EventArgs e)
        {
            StartPlayThread();
        }

        /// <summary>
        /// 启动TTS播放线程
        /// </summary>
        private void StartPlayThread() {
            if (playTtsThread != null)
                return;
            playTtsThread = new Thread(PlayThread);
            playTtsThread.IsBackground = true;
            playTtsThread.Start();
        }

        /// <summary>
        /// 停止TTs播放线程
        /// </summary>
        private void StopPlayThread() {
            if(playTtsThread == null) return;
            isRun = false;
            Thread.Sleep(200);
            playTtsThread.Abort();
            playTtsThread = null;
        }

        /// <summary>
        /// TTS的播放线程函数
        /// </summary>
        private void PlayThread() {
            SpeechSynthesizer speechSyn = new SpeechSynthesizer();
            string txt = "语音测试，0123456789，进行了数字测试，这是报警测试demo!";
            isRun = true;
            while (isRun) {
                this.Invoke(new EventHandler(delegate {
                    laReq.ForeColor = Color.Gray;
                    laSucceed.ForeColor = Color.Gray;
                    laPlay.ForeColor = Color.Gray;
                }));
                Thread.Sleep(250);
                //this.Invoke(new EventHandler(delegate { }));
                this.Invoke(new EventHandler(delegate
                {
                    laReq.ForeColor = Color.Green;
                }));
                //请求
                //HttpReq("http://localhost:8088/api/getfirstalarmmessage");
                //HttpReq("http://192.168.10.143:8088/api/getfirstalarmmessage");
                //处理请求结果
                this.Invoke(new EventHandler(delegate
                {
                    laSucceed.ForeColor = Color.Green;
                }));
                //播放语音
                this.Invoke(new EventHandler(delegate
                {
                    laPlay.ForeColor = Color.Green;
                }));
                speechSyn.Speak(txt);
                Thread.Sleep(50);
            }
        }

        private void FrmPlayTts_FormClosing(object sender, FormClosingEventArgs e)
        {
            StopPlayThread();
        }

        //public static string HttpReq(string url)
        //{

        //    string devSn = this.txtDevSn.Text;
        //    // 构造Json数据字符串
        //    string jsonData = JsonConvert.SerializeObject(new SConditions() { devSn = devSn });
        //    // 调用HttpPost方法
        //    string json = PostRequest(jsonData, url);
        //    JObject jsonObj = JObject.Parse(json);
        //    var info = (JObject)jsonObj["info"];
        //    devId = Convert.ToInt32(info["id"].ToString());
        //    return "";
        //}

        public static string PostRequest(string content, string url, string contentType = "application/json")
        {
            try
            {
                var memStream = new MemoryStream();
                var cc = Encoding.UTF8.GetBytes(content);
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = contentType;
                memStream.Write(cc, 0, cc.Length);
                request.ContentLength = memStream.Length;
                var requestStream = request.GetRequestStream();
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
                string responseTxt = string.Empty;
                WebResponse response = request.GetResponse();
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    responseTxt = reader.ReadToEnd();
                }
                response.Close();
                return responseTxt;
            }
            catch (Exception ex)
            {
                Debug.Print($"异常位置：FrmMain ---- >> PostRequest，异常信息：{ex.Message}");
                return "";
            }
        }
    }
}
